package com.usf.jprovider.object.builder;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;

import com.usf.jprovider.object.JObjectNode;

public class SQLBuilder {
	
	private String table;
	private List<JObjectNode> primary;
	private LinkedHashMap<String, String> columns;
	
	public SQLBuilder(String table) {
		this.table = table;
		this.primary =  new ArrayList<JObjectNode>();
		this.columns = new LinkedHashMap<String, String>();
	}
	
	public void add(String key, String value){
		this.columns.put(key, value);
	}
	public void addPrimary(JObjectNode node){
		this.primary.add(node);
	}
	
	public String toSQL() {
		Iterator<String>keys = columns.keySet().iterator();
		if(!keys.hasNext())return null;
		String key = keys.next();
		StringBuilder query = new StringBuilder("INSERT INTO " + table + "(" + key);
		StringBuilder values = new StringBuilder("VALUES(" + columns.get(key));
		while(keys.hasNext()){
			key = keys.next();
			query.append(", " + key);
			values.append(", " + columns.get(key));
		}
		values.append(");");
		query.append(") ");
		query.append(values);
		return query.toString();	
	}
	
	public String[] primaryKeys(){
		String[] keys = new String[primary.size()];
		for(int i=0; i<primary.size(); i++)
			keys[i] = primary.get(i).getName();
		return keys;
	}
	
	public void persist(Connection connection) throws Exception {
		Statement stat = connection.createStatement();
		stat.executeUpdate(toSQL(), primaryKeys()); //Statement.RETURN_GENERATED_KEYS
		ResultSet rs= stat.getGeneratedKeys();
		if(!rs.next()) return; // Error if primary.lenght > 0
		for(int i=0; i < primary.size(); i++)
			primary.get(i).changeValue(rs.getObject(i+1).toString());
	}
	
	
}
